HDU 1032 [The 3n + 1 problem] 暴力模拟

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1032

题目大意:给出i,j,要求输出i j之间“3N+1”的循环次数的最大值。

关键思想:暴力,模拟。可以优化,因为某些大数在进行操作时,会变为已经求过的小数,之后的循环次数已求过。

代码如下:

//between i,j  模拟,暴力 
#include <iostream>
#include <algorithm>
using namespace std;
int i,j;
int main(){
	long long MAX,temp,cnt;
	while(cin>>i>>j){
		MAX=0;
		int s=min(i,j),l=max(i,j);//输入i可以大于j 
		for(int a=s;a<=l;a++){
			cnt=1;
			temp=a;
			while(temp>1){
				if(temp%2==1){
					temp=3*temp+1;
					temp/=2;
					cnt+=2;
				}else{
					temp/=2;
					cnt++;
				}
			}
			MAX=max(cnt,MAX);
		}
		cout<<i<<" "<<j<<" "<<MAX<<endl;
	}
	return 0;
}

  

posted @ 2017-02-18 11:16  哇咔咔咔  阅读(252)  评论(0编辑  收藏  举报